package com.sharemarking.wa.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.platform.dto.driver.DriverListDto;
import com.sharemarking.wa.platform.dto.driverVerify.DriverAttachmentDto;
import com.sharemarking.wa.platform.dto.driverVerify.DriverVerifyDto;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author dxy
 */
@Service
public class DriverService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private DriverVerifyMapper driverVerifyMapper;
    @Autowired
    private DriverAttachmentMapper driverAttachmentMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private OrgCarMapper orgCarMapper;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private CarManagementMapper carManagementMapper;
    public ResponseParams<?> getDriverInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String driverId = request.getParameter("driverId");

        if (StringUtils.isEmpty(driverId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("driverId"));
        }

        QueryWrapper<DriverVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", driverId);
        DriverVerify driverVerify = driverVerifyMapper.selectOne(queryOne);
        Car car = carManagementMapper.getCarInfoByDriverId(Integer.parseInt(driverId));

        //判断权限
//        if (!driverVerify.getOrgId().equals(orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id", memberId)).getOrgId())) {
//            throw RequestException.create(ResponseParams.isDataError("无权限"));
//        }


        //获取证件信息
        QueryWrapper<DriverAttachment> queryTwo = new QueryWrapper<>();
        queryTwo.eq("driver_verify_id", driverVerify.getId());
        List<DriverAttachment> driverAttachment = driverAttachmentMapper.selectList(queryTwo);


        //将实体转为dto
        List<DriverAttachmentDto> driverAttachmentDtoList = new ArrayList<>();
        for (DriverAttachment dt : driverAttachment) {
            DriverAttachmentDto driverAttachmentDto = new DriverAttachmentDto();
            BeanUtils.copyProperties(dt, driverAttachmentDto);
            driverAttachmentDtoList.add(driverAttachmentDto);
        }


        DriverVerifyDto driverVerifyListDto = new DriverVerifyDto();
        BeanUtils.copyProperties(driverVerify, driverVerifyListDto);
        driverVerifyListDto.setVerifyList(driverAttachmentDtoList);
        if (!ObjectUtils.isEmpty(car)) {
            driverVerifyListDto.setCarWeight(car.getCarWeight());
            driverVerifyListDto.setCarType(car.getType());
            driverVerifyListDto.setCarNumber(car.getNumber());
        }
        return ResponseParams.ok(driverVerifyListDto);
    }

    public ResponseParams<?> delete() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String driverId = request.getParameter("driverId");

        if (StringUtils.isEmpty(driverId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("driverId"));
        }

        QueryWrapper<DriverVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", driverId);
        DriverVerify driverVerify = driverVerifyMapper.selectOne(queryOne);

        //判断权限
        if (!driverVerify.getOrgId().equals(orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().select("org_id").eq("member_id", memberId)).getOrgId())) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }
        //删除org_member
        orgMemberMapper.delete(new QueryWrapper<OrgMember>().eq("member_id",driverId));
        //删除证件
        driverAttachmentMapper.deleteByMemberId(Integer.valueOf(driverId));
        //删除driver_verify
        driverVerifyMapper.delete(queryOne);
        //member里面的real_name置为null
        memberMapper.updateRealNameNull(Integer.valueOf(driverId));
        return ResponseParams.ok(null);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> exam() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String driverId = request.getParameter("driverId");
        String stateExam = request.getParameter("stateExam");
        String rejectReason = request.getParameter("rejectReason");

        if (StringUtils.isEmpty(driverId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("driverId"));
        }
        if (!stateExam.equals("1") && !stateExam.equals("2")) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("stateExam"));
        }
        if (stateExam.equals("2")) {
            if (StringUtils.isEmpty(rejectReason)) {
                throw RequestException.create(ResponseParams.requiredParamsIsMissing("rejectReason"));
            }
        }


        QueryWrapper<DriverVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", driverId);
        DriverVerify driverVerify = driverVerifyMapper.selectOne(queryOne);

        //判断权限,获取调度员的orgId
        Integer orgId = orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().select("org_id").eq("member_id", memberId)).getOrgId();
        if (!driverVerify.getOrgId().equals(orgId)) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        DriverVerify d = new DriverVerify();
        d.setExamState(Integer.valueOf(stateExam));
        d.setRejectReason(rejectReason);
        d.setMemberId(Integer.valueOf(driverId));
        d.setUpdateDate(new Date());
        d.setId(driverVerify.getId());
        driverVerifyMapper.updateById(d);

        String messageStr = null;
        if (stateExam.equals("1")) {
            //如果通过司机认证，把认证名字冗余到用户表中的真实名字
            Member member = new Member();
            member.setRealName(driverVerify.getName());
            member.setId(driverVerify.getMemberId());
            member.setUpdateDate(new Date());
            memberMapper.setRealName(member);

            if (orgMemberMapper.selectCount(new QueryWrapper<OrgMember>().eq("member_id", driverId)) == 0) {
                //同时在org_member表中插入记录
                OrgMember orgMember = new OrgMember();
                orgMember.setOrgId(orgId);
                orgMember.setMemberId(Integer.valueOf(driverId));
                orgMember.setCreateDate(new Date());
                orgMemberMapper.insert(orgMember);
            }

            messageStr = "您好，您的司机认证已通过。";
        }else if (stateExam.equals("2")) {
            //被驳回
            orgMemberMapper.delete(new QueryWrapper<OrgMember>().eq("member_id", driverId));
            messageStr = "您好，您的司机认证已被驳回，驳回理由是："+rejectReason;
        }

        if (!ObjectUtils.isEmpty(memberMapper.get(Integer.valueOf(driverId))))
            jgPushService.pushTag(messageStr, Integer.valueOf(driverId));
        else
            jgPushService.pushTag(messageStr, orgCarMapper.selectById(Integer.valueOf(driverId)).getDriverId());
        return ResponseParams.ok(null);
    }

    public ResponseParams<?> getDriverList() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        Integer role = memberMapper.getRoleByMemberId(memberId);

        if (!role.equals(3) && !role.equals(4)) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }

        Integer orgId = orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id", memberId)).getOrgId();
        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);
        params.put("orgId", orgId);


        List<DriverListDto> list = driverMapper.getDriverList(params);

        for (DriverListDto d : list) {
            d.setTaskList(driverMapper.getCodeListByDriverId(d.getDriverId()));
        }

        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, driverMapper.getDriverListToatl(params), list.size() == pageSize));
    }
}
